<template>
  <el-card style="max-width: 480px; border-radius: 10px">
    <div class="title">
      <h1>vue3-element-admin</h1>
    </div>
    <div class="login">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入用户名" />
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="ruleForm.password" placeholder="请输入密码" type="password" />
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-form-item>
        <!-- <el-form-item prop="code">
          <el-input v-model="ruleForm.code" placeholder="请输入验证码" />
        </el-form-item> -->
      </el-form>
    </div>
    <div class="btn">
      <el-button type="primary" :style="loginBtn" @click="onSubmit">登录</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { roleLogin } from '@/service/study5/demo2'
import { useRouter } from 'vue-router'

interface RuleForm {
  username: string
  password: string 
  code: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  username: '',
  password: '',
  code: ''
})

const loginData = {
  username: '',
  password: ''
}

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: '用户名不能为空！', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空！', trigger: 'blur' }],
  code: [{ required: true, message: '验证码不能为空！', trigger: 'blur' }]
})
const router = useRouter()
/**
 * 登录验证
 */
const onSubmit = async () => {
  loginData.username = ruleForm.username
  loginData.password = ruleForm.password
  const res = await roleLogin(loginData)

  localStorage.setItem('token', res.data)
  console.log(res.data)
  // router.replace()方法进行页面跳转。
  router.replace('/studemo62/user')
}

// 定义登录按钮样式
const loginBtn = {
  width: '420px',
  height: '40px',
  backgroundColor: 'rgb(90,156,248)',
  color: '#fff',
  textAlign: 'center',
  marginTop: '15px',
  border: 'none'
}
</script>

<style scoped>
.title {
  margin: 30px auto 15px;
  text-align: center;
}
.login {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
</style>
